# Copyright (C) 2007 Samuel Abels, http://debain.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
import re
from Scope   import Scope
from Define  import Define
from Grammar import Grammar

varname_re = r'[a-zA-Z][\w_]+'
keywords   = ['define', 'grammar']

grammar = (
    ('escaped_data',        r'\\.'),
    ('regex_delimiter',     r'/'),
    ('string_delimiter',    r'\''),
    ('comma',               r','),
    ('colon',               r':'),
    ('equals',              r'='),
    ('semicolon',           r';'),
    ('open_edge_bracket',   r'\['),
    ('close_edge_bracket',  r'\]'),
    ('minus',               r'-'),
    ('keyword',             r'\b(?:' + '|'.join(keywords)  + r')\b'),
    ('open_curly_bracket',  '{'),
    ('close_curly_bracket', '}'),
    ('whitespace',          r'[ \t]+'),
    ('open_function_call',  varname_re + r'(?:\.' + varname_re + r')*\('),
    ('close_bracket',       r'\)'),
    ('varname',             varname_re),
    ('newline',             r'[\r\n]'),
    ('comment',             r'#[^\r\n]+'),
    ('raw_data',            r'[^\r\n{}\\]+')
)

grammar_c = []
for type, regex in grammar:
    grammar_c.append((type, re.compile(regex)))

class Global(Scope):
    def __init__(self, parser, parent, *args, **kwargs):
        Scope.__init__(self, 'Global', parser, parent, **kwargs)
        parser.set_grammar(grammar_c)
        #print "Opening Scope:", parser.token()
        buffer = ''
        while 1:
            if self.exit_requested or parser.current_is('EOF'):
                break
            elif parser.next_if('comment'):
                continue
            elif parser.next_if('whitespace'):
                continue
            elif parser.next_if('newline'):
                continue
            elif parser.current_is('keyword', 'define'):
                define = Define(parser, self)
                self.children.append(define)
            elif parser.current_is('keyword', 'grammar'):
                define = Grammar(parser, self)
                self.children.append(define)
            else:
                type, tok = parser.token()
                parent.syntax_error(self, 'Unexpected %s %s' % (type, repr(tok)))
        parser.restore_grammar()


    def value(self):
        for child in self.children:
            child.value()
